<?php
declare (strict_types = 1);

namespace app\admin\controller\erp;

use app\admin\controller\AuthController;
use app\admin\model\erp\ErpGoods;
use app\admin\model\erp\ErpGoodsTypes;
use app\admin\model\erp\ErpSubjects;
use app\admin\model\erp\Vendors;
use app\admin\model\system\SystemMenus;
use bbweb\services\UtilService as Util;
use think\Exception;
use think\facade\Config;
use think\Request;

class Basics extends AuthController
{
    /**
     * 显示列表
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function index(Request $req)
    {
        if ($req->isAjax()) {
            $data = [];
            $page = $req->param('page/d', 1);
            $limit = $req->param('limit/d', 15);
            $query = ErpGoods::order('id DESC');
            // 条件搜索
            $code = $req->param('code');
            if (!is_null($code) && strlen($code) && $code != 0) {
                $query->where('code','like',"{$code}%");
            }
            $name = $req->param('name');
            if (!is_null($name) && strlen($name)) {
                $query->where('name','like',"%$name%");
            }
            //$query->order('id DESC');
            $data['count'] = $query->count('id');
            $data['data'] = $query->page($page,$limit)->select()->toArray();
            //echo $query->getLastSql();
            $data['code'] = 0;
            $data['msg'] = '';
            $units = Config::get('erp.erp_units');
            foreach ($data['data'] as &$val) {
                $val['unit'] = $units[$val['unit']] ?? '';
            }

            return json($data);
        }
        $sonAuth = SystemMenus::getSonAuth($req->controller(), $req->action(),array_keys($this->auth));

        $treeData = ErpGoodsTypes::typeAll(1);
        // 显示页面
        $this->assign('sonAuth', $sonAuth);
        $this->assign('treeData', $treeData);
        return $this->fetch();
    }

    /**
     * 创建资源.
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function add(Request $req)
    {
        if($req->isPost()) {
            $op = $req->param('op','yes');
            if($op == 'getTree') {
                $tree = ErpGoodsTypes::typeAll();
                return json($tree);
            } else {
                $data = Util::postMore([
                    ['name',''],//名称
                    ['norm',''],//规格
                    ['tid', 0],//物料组
                    ['unit', 1],//单位
                    ['vid', 0],//默认供应商
                    ['factory',''],//默认生产厂家
                    ['bar_code',''],//条形码
                    ['check_out', 0],//强制序列号
                    ['max_stock', 0],//最大库存量
                    ['min_stock', 0],//最小库存
                    ['price', 0],//实际成本
                    ['retail_price', 0],//零售报价
                    ['retail_price_limit', 0],//零售限价
                    ['agent_price', 0],//分销报价
                    ['agent_price_limit', 0],//分销限价
                ], $req);
                if (!$data['name']) $this->error('请输入商品名称');
                if (!$data['tid']) $this->error('请选择物料组');
                $data['price'] = round($data['price'], 2);
                $data['retail_price'] = round($data['retail_price'], 2);
                $data['retail_price_limit'] = round($data['retail_price_limit'], 2);
                $data['agent_price'] = round($data['agent_price'], 2);
                $data['agent_price_limit'] = round($data['agent_price_limit'], 2);
                $data['create_at'] = time();
                $data['update_at'] = time();

                $sub = ErpSubjects::where('rel_id', '=', $data['tid'])->where('rel_type','=','type')->find();
                if(!$sub) $this->error('选择物料组没有对应会计科目');
                $level = $sub['level'] + 1;
                $code = ErpSubjects::where('code','like', "{$sub['code']}%")->where('level',$level)->max('code');
                if($code <= $sub['code']) $code = $sub['code'] . '000';
                $code = $code + 1;
                $data['code'] = $code;

                ErpGoods::beginTrans();
                try {
                    $res = ErpGoods::create($data);
                    if($res && $res->id) {
                        $info = $res->toArray();
                        $item = [
                            'pid'       => $sub['id'],
                            'rel_id'    => $info['id'],
                            'rel_type'  => 'good',
                            'code'      => $code,
                            'name'      => $info['name'],
                            'pname'     => $sub['pname'],
                            'level'     => $level,
                            'luck'      => 1,
                            'edit_luck' => 1,
                            'update_at' => time()
                        ];
                        $sb = ErpSubjects::create($item);
                        if(!$sb) {
                            throw new \think\Exception('新商品对应会计科目写入失败！');
                        }
                    } else {
                        throw new \think\Exception('商品保存失败！');
                    }
                    ErpGoods::commitTrans();
                } catch (\Exception $e) {
                    ErpGoods::rollbackTrans();
                    $this->error($e->getMessage());
                }
                $this->success('操作成功!');
            }
        }
        $units = Config::get('erp.erp_units');
        $users = Vendors::where('type',1)->column('id,name,phone', 'id');
        $this->assign('users', $users);
        $this->assign('units', $units);
        return $this->fetch();
    }

    /**
     * 更新资源
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function edit(Request $req)
    {
        $id = intval($req->param('id/d'));
        if(!$id) $this->error('无效参数','', -1);
        $good = ErpGoods::find($id);
        if(!$good) $this->error('无效参数','', -1);
        if($req->isPost()) {
            $data = Util::postMore([
                ['name',''],//名称
                ['norm',''],//规格
                ['unit', 1],//单位
                ['vid', 0],//默认供应商
                ['factory',''],//默认生产厂家
                ['bar_code',''],//条形码
                ['check_out', 0],//强制序列号
                ['max_stock', 0],//最大库存量
                ['min_stock', 0],//最小库存
                ['price', 0],//实际成本
                ['retail_price', 0],//零售报价
                ['retail_price_limit', 0],//零售限价
                ['agent_price', 0],//分销报价
                ['agent_price_limit', 0],//分销限价
                ['status', 1],
            ], $req);
            if (!$data['name']) $this->error('请输入商品名称');
            $data['price'] = round($data['price'], 2);
            $data['retail_price'] = round($data['retail_price'], 2);
            $data['retail_price_limit'] = round($data['retail_price_limit'], 2);
            $data['agent_price'] = round($data['agent_price'], 2);
            $data['agent_price_limit'] = round($data['agent_price_limit'], 2);
            $data['create_at'] = time();
            $data['update_at'] = time();

            $sub = ErpSubjects::where('rel_id', '=', $good['id'])->where('rel_type','=','good')->find();
            if(!$sub) $this->error('商品没有对应会计科目');
            $sub_up = $good['name'] != $data['name'] ? true : false;
            ErpGoods::beginTrans();
            try {
                $res = ErpGoods::where('id', $id)->update($data);
                if($res) {
                    $item = [
                        'name'      => $data['name'],
                        'update_at' => time()
                    ];
                    if($sub_up) {
                        $sb = ErpSubjects::where('rel_id', $id)->where('rel_type','=','good')->update($item);
                        if (!$sb) {
                            throw new \think\Exception('新商品对应会计科目修改失败！');
                        }
                    }
                } else {
                    throw new \think\Exception('商品保存失败！');
                }
                ErpGoods::commitTrans();
            } catch (\Exception $e) {
                ErpGoods::rollbackTrans();
                $this->error($e->getMessage());
            }
            $this->success('操作成功!');
        }
        $units = Config::get('erp.erp_units');
        $treeData = ErpGoodsTypes::where('id',$good['tid'])->column('name','id');
        $users = Vendors::where('type',1)->column('id,name,phone', 'id');
        $this->assign('treeData', $treeData);
        $this->assign('users', $users);
        $this->assign('units', $units);
        $this->assign('good', $good);
        return $this->fetch();
    }

    /**
     * 显示分类列表
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function types(Request $req)
    {
        $data = ErpGoodsTypes::getAll();

        $sonAuth = SystemMenus::getSonAuth($req->controller(), 'index',array_keys($this->auth));
        // 显示页面
        $this->assign('sonAuth', $sonAuth);
        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * 创建分类.
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function addType(Request $req)
    {
        $id = intval($req->param('id/d'));
        if(!$id) $this->error('无效参数','', -1);
        $type = ErpGoodsTypes::find($id);
        if(!$type) $this->error('无效参数','', -1);
        $level = $type['level'] + 1;
        if ($req->isPost()) {
            $names = $req->param('names','');
            if (!$names) $this->error('请输入类别名称');
            $names = explode("\n", $names);
            $n = 0;
            $data = [];
            foreach($names as $val) {
                $name = trim($val);
                if(!empty($name)) {
                    if(ErpGoodsTypes::where('name','=',$name)->where('pid','=',$id)->find()) continue;
                    $item = [
                        'pid' => $id,
                        'name' => $name,
                        'level' => $level,
                        'update_at' => time()
                    ];
                    $res = ErpGoodsTypes::addType($type,$item);
                    if($res && !empty($res)) {
                        $data[] = $res;
                        $n++;
                    }
                }
            }
            if($n > 0) {
                return json(['code' => 2, 'msg' => '成功写入' . $n . '条分类', 'data' => $data]);
            } else {
                $this->error();
            }
        }
        return $this->fetch();
    }

    /**
     * 更新分类
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function editType(Request $req)
    {
        $id = $req->param('id/d');
        $type = ErpGoodsTypes::find($id);
        if(empty($type)) {
            $this->error('参数错误！','',-1);
        }
        if ($req->isPost()) {
            $name = $req->param('name','');
            if (!$name) $this->error('请输入类别名称');
            $data = [
                'name' => $name,
                'update_at' => time()
            ];
            ErpGoodsTypes::beginTrans();
            try {
                $res = ErpGoodsTypes::where('id','=',$id)->update($data);
                if(!$res) {
                    throw new \think\Exception('分类名称修改失败！');
                }
                $res = ErpSubjects::where('rel_id',$id)->where('rel_type','=','type')->update($data);
                if(!$res) {
                    throw new \think\Exception('会计科目同步失败！');
                }
                ErpGoodsTypes::commitTrans();
            } catch (Exception $e) {
                ErpGoodsTypes::rollbackTrans();
                return json(['code'=>0, 'msg'=>$e->getMessage()]);
            }
            $type = ErpGoodsTypes::find($id);
            return json(['code'=>1, 'msg'=>'修改成功','data'=>$type]);

        }
        $this->assign('type',$type);
        return $this->fetch();
    }
}
